"""
@Time : 2022/9/16 15:55 
@Author : ls
@DES: 
"""
from multiprocessing import Queue
import numpy
from fastapi import WebSocket
from models.custom_class import CoalYard


class CloudSender(object):
    def __init__(self, coal_yard: CoalYard, queue=None, websocket=None):
        self.coal_yard = coal_yard
        self._queue = queue
        self._websocket = websocket
        self._matrix = None
        self.cloud_buffer = []
        self.cloud_status = None

    def set_queue(self, queue):
        self._queue = queue

    def set_matrix(self, matrix: dict):
        self._matrix = matrix

    def set_websocket(self, websocket: WebSocket):
        self._websocket = websocket

    def send_cloud(self):
        while True:
            if not self._queue.empty():
                data = self._queue.get()
                if isinstance(data, dict):
                    for key, value in data.items():
                        radars = self.coal_yard.coalRadarList
                        for radar in radars:
                            if key == radar.id:
                                cloud = numpy.frombuffer(value, dtype=numpy.int16).reshape(-1, 3)
                                div = numpy.array([100, 100, 100])
                                cloud = numpy.divide(cloud, div)
                                cloud = numpy.insert(cloud, 3, values=1.0, axis=1)
                                matrix = self._matrix[radar.ip]
                                cloud = numpy.dot(numpy.array(matrix), cloud.T)
                                cloud = cloud.T
                                cloud = cloud[:, :3]
                                self.cloud_buffer.append(cloud)
                                cloud = str(cloud.tolist())
                                self._websocket.send_text(cloud)
                else:
                    break
        self.cloud_status = True

    def get_cloud(self):
        if self.cloud_status is True:
            cloud = numpy.concatenate(self.cloud_buffer, axis=0)
            return cloud
